<template>
  <div class="my-edit-container">
    <div class="title-bd">
      <div class="title-name">{{title}}</div>
      <div class="hr"></div>
      <!-- <el-button class="btn-submit" type="primary" @click="submitForm">提 交</el-button> -->
    </div>
    <div class="myForm">
      <el-form class="my-form_wrapper" ref="form" id="editShareInfoForm" :model="form" :inline="true" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型" porp="shareType">
              <el-select v-model="form.shareType" placeholder="请选择类型">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 22px;">
          <div id="goodsInfoBox">
            <div class="info">
              <!-- <div>
                <el-form-item label="商品id" prop="goodsId" style="width: 100%;">
                  <el-input v-model="form.goodsId" placeholder="请点击右侧按钮选择商品" @clear="clearSelectedGoods" clearable class="my-el-input input-with-select">
                    <el-button v-on:click.native="openProductSelector()" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                </el-form-item>
              </div> -->
              <div style="width: 100%;">
                <el-form-item label="商品名称" style="width: 100%;" porp="goodsName">
                  <el-input v-model="form.goodsName" disabled placeholder="请点击右侧按钮选择商品" @clear="clearSelectedGoods" clearable class="my-el-input input-with-select">
                    <el-button v-on:click.native="openProductSelector()" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                </el-form-item>
              </div>
            </div>
            <img v-if="form.shopGoods && form.shopGoods.goodsImg" class="img" :src="form.shopGoods.goodsImg" alt="商品图片" @click="handlePicPreview2(form.shopGoods.goodsImg)">
          </div>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="文案" style="width: 100%;" prop="shareInfo" >
              <el-input class="my-el-input" type="textarea" :rows="4" v-model="form.shareInfo" placeholder="请输入文案"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" style="width: 100%;" prop="shareRemark" >
              <el-input class="my-el-input" v-model="form.shareRemark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="广告位">
            <div id="uploadPicBox">
              <el-upload :action="uploadActionAdvert" :headers="uploadHeaders" :multiple="false" :file-list="advertPic"
                list-type="picture-card" :on-success="handleUploadSuccAdvert">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete" @click="handlePicRemove(file, advertPic)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="图片(最多9张)">
            <div id="uploadPicBox">
              <el-upload :action="uploadActionMain" :headers="uploadHeaders" :multiple="false" :file-list="mainPic"
                list-type="picture-card" :limit='9' :on-success="handleUploadSuccMain">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span class="el-upload-list__item-delete" @click="handlePicRemove(file, mainPic)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
            </div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="视频地址" style="width: 100%;">
              <el-input v-model="videoUrl" disabled="disabled" placeholder="请上传视频" />
              <div class="video-opra-btns">
                <el-upload v-if="!videoUrl" ref="upload" :action="uploadActionMain2" :headers="uploadHeaders"
                  :show-file-list="false" :on-success="handleVideoSuccess" :on-progress="uploadVideoProcess" accept="video/mp4,video/ogg,video/flv,video/avi,video/wmv,video/rmvb"
                  :before-upload="beforeUploadVideo" class="video-uploader">
                  <el-button type="primary" plain icon="el-icon-file" size="mini">上传视频</el-button>
                </el-upload>
                <el-button style="margin-left: 15px;height: 30px;" v-if="videoUrl && videoUrl.length>0" type="success"
                  plain icon="el-icon-file" size="mini" @click="winOpen()">查看视频</el-button>
                <el-button style="margin-left: 15px;height: 30px;" v-if="videoUrl && videoUrl.length>0" type="info"
                  plain size="mini" @click="clearvideoUrl()">重置视频地址</el-button>
              </div>
            </el-form-item>
            <el-form-item v-if="videoFlag == true" label="上传进度">
              <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="my-form-footer">
              <el-button type="primary" @click="submitForm">提 交</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-dialog :visible.sync="showPicPreview">
      <img width="100%" :src="picPreviewUrl" alt="">
    </el-dialog>

    <!-- 新增界面-选择商品信息 -->
    <el-dialog fullscreen append-to-body center :close-on-click-modal="false" :close-on-press-escape="false" title="请选择1件商品"
      :visible.sync="isSelectProduct" :before-close="closeProductSelector">
      <product-selector isComponent="true" @onSelect="onSelect" @onCancel="closeProductSelector"></product-selector>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listInfo,
    getInfo,
    delInfo,
    addInfo,
    updateInfo,
    exportInfo
  } from "@/api/share/info";
  import ProductSelector from "@/components/ProductSelector";
  import {
    addFile,
    delFiles,
    getFileList,
    editFile,
    getPreId
  } from "@/api/basic/file"

  export default {
    name: "InfoEdit",
    components: {
      ProductSelector
    },
    data() {
      return {
        id: "",
        opraType: 'add',
        videoId: "",
        videoUrl: "",
        isSelectProduct: false,
        selectProducts: [],
        showPicPreview: false,
        picPreviewUrl: "",
        mainPic: [],
        advertPic: [],
        // 类型字典
        typeOptions: [],
        videoUploadPercent: 0, // 视频上传进度
        picUploadPercent: 0, // 视频上传进度
        picFlag: false,
        videoFlag: false,
        uploadActionMain: "",
        uploadActionMain2: "",
        uploadActionAdvert:"",
        uploadHeaders: {
          Authorization: 'Bearer ' + this.$store.state.user.token,
          lesseeId: this.$store.state.user.lesseeid || '13'
        },
        // 总条数
        total: 0,
        // 标题
        title: "",
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          shareType: [
            { required: true, message: "请选择类型", trigger: "blur" },
          ],
          goodsName: [
            { required: true, message: "请选择商品", trigger: "blur" },
          ],
          shareInfo: [
            { required: true, message: "请输入文案", trigger: "blur" },
          ],
          shareRemark: [
            { required: true, message: "请输入备注", trigger: "blur" },
          ]
        }
      };
    },
    created() {
      var that = this;
      that.getDicts("SHOP_SHARE_INFO").then(response => {
        that.typeOptions = response.data;
      });
      const id = that.$route.params.id;
      if (id === 'add') {
        that.opraType = 'add';
        that.title = '添加素材圈';
        that.reset(function(){
          that.setUploadAction(that.form.id);
        });
      } else {
        that.opraType = 'edit';
        that.title = '编辑素材圈';
        getInfo(id).then(response => {
          that.form = response.data;
          that.form.goodsName = that.form.shopGoods.goodsName || '';
          if(that.form.advertPic){
            that.advertPic = [{url:that.form.advertPic}]
          }
          that.setUploadAction(that.form.id);
          // 根据url创建文件对象：
          if (that.form.id) {
            // 获取视频
            getFileList({
              sourcessId: that.form.id,
              sourcessType: 'MATERIALVIDEO'
            }).then(rs => {
              if (rs.code == 200) {
                const list = rs.data || rs.rows || [];
                if (list.length > 0) {
                  that.videoUrl = list[0].fileFullUrl;
                  that.videoId = list[0].id;
                }
              }
            })
            // 获取图片
            getFileList({
              sourcessId: that.form.id,
              sourcessType: 'MATERIALIMAGE'
            }).then(rs => {
              if (rs.code == 200) {
                that.mainPic = rs.data || rs.rows || [];
                if (that.mainPic.length > 0) {
                  that.mainPic.forEach(function(item) {
                    item.url = item.fileFullUrl;
                  })
                }
              }
            })
          }
        });
      }
    },
    methods: {
      // 表单重置
      reset(call) {
        const that = this;
        getPreId({}).then(response => {
          if (response.code !== 200) {
            that.msgError(response.msg)
          } else {
            that.id = response.data.id;
            console.log('preId:'+that.id);
             that.form = {
               id: response.data.id,
               createBy: that.$store.state.user.name || '',
               createTime: undefined,
               updateBy: that.$store.state.user.name || '',
               updateTime: undefined,
               isActive: '1',
               lesseeId: that.$store.state.user.lesseeid || '13',
               goodsId: undefined,
               goodsName: undefined,
               shareInfo: undefined,
               shareType: undefined,
               shareRemark: undefined
             };
             that.resetForm("form");
             setTimeout(function(){
               if (call) {
                 call();
               }
             }, 40)
          }
        })
      },
      handlePicPreview2(url) {
        if (url) {
          var file = {};
          file.url = url;
          this.handlePicPreview(file);
        }
      },
      handlePicPreview(file) {
        this.picPreviewUrl = file.url
        this.showPicPreview = true
      },
      handlePicRemove(file, fileList) {
        return this.$confirm('确定删除该图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let fileId = file.id || (file.response?(file.response.fileId):'')
          if (fileId) {
            delFiles({
              ids: fileId
            }).then(response => {
              if (response.code !== 200) {
                this.msgError(response.msg)
              } else {
                let findIndex = fileList.findIndex(obj => {
                  return obj.uid == file.uid
                })
                if (findIndex >= 0) {
                  fileList.splice(findIndex, 1)
                }
              }
            })
          } else {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            let findIndex = fileList.findIndex(obj => {
              return obj.uid == file.uid
            })
            if (findIndex >= 0) {
              fileList.splice(findIndex, 1)
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleUploadSuccMain(response, file, fileList) {
        console.log('上传的文件:');
        console.log(file);
        this.mainPic.push(file);
      },
      handleUploadSuccAdvert(response, file, fileList) {
        console.log('上传的文件:');
        console.log(file);
        this.advertPic = [file];
      },
      setUploadAction(id) {
        this.uploadActionMain = process.env.VUE_APP_BASE_API + '/common/upload/material?sourcessId=' + id +
          '&sourcessType=MATERIALIMAGE&isActive=是';
        this.uploadActionMain2 = process.env.VUE_APP_BASE_API + '/common/upload/material?sourcessId=' + id +
          '&sourcessType=MATERIALVIDEO&isActive=是';
        this.uploadActionAdvert = process.env.VUE_APP_BASE_API + '/common/upload/material?sourcessId=' + id +
          '&sourcessType=MATERIALADVERT&isActive=是';
      },
      clearSelectedGoods() {
        this.selectProducts = [];
        this.form.goodsId = "";
        this.form.goodsName = "";
        this.form.shopGoods = null;
      },
      openProductSelector() {
        const that = this;
        that.selectedList = [];
        that.isSelectProduct = true;
      },
      closeProductSelector() {
        this.isSelectProduct = false;
      },
      onSelect(selectProducts) {
        if (!selectProducts || selectProducts.length === 0) return;
        const product = selectProducts[0];
        if (this.goodsId === product.id) return;
        this.form.goodsId = product.id;
        this.form.goodsName = product.goodsName;
        this.form.shopGoods = product;
      },
      handleVideoSuccess(res, file) { //获取上传图片地址
        const that = this;
        that.videoFlag = false;
        that.videoUploadPercent = 0;
        console.log('上传结果');
        console.log(res);
        if (res.code == 200) {
          that.videoUrl = res.url;
          that.videoId = res.fileId;
        } else {
          that.$message.error('视频上传失败，请重新上传！');
        }
      },
      beforeUploadVideo(file) {
        const isLt50M = file.size / 1024 / 1024 < 50;
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) == -1) {
          this.$message.error('请上传正确的视频格式');
          return false;
        }
        if (!isLt50M) {
          this.$message.error('视频' + (file.size / 1024 / 1024) + 'MB, 超过50MB！请另选视频!');
          return false;
        }
      },
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = Number(file.percentage.toFixed(0));
      },
      winOpen() {
        const that = this;
        if (!that.videoUrl) {
          return;
        }
        window.open(that.videoUrl, "_blank");
      },
      clearvideoUrl() {
        const that = this;
        if (!that.videoId) {
          return;
        }
        delFiles({
          ids: that.videoId
        }).then(response => {
          if (response.code !== 200) {
            that.msgError(response.msg)
          } else {
            that.videoUrl = '';
            that.videoId = '';
          }
        })
      },
      /** 提交按钮 */
      submitForm: function() {
        var that = this;
        that.$refs["form"].validate(valid => {
          if (valid) {
            var params = that.form;
            delete params.goodsName;
            console.log(params)
            if(that.advertPic.length){
              that.form.advertPic = that.advertPic[0].response.url
            }else{
              that.form.advertPic = ''
            }
            if(params.shareType=='MAIN' && !params.advertPic){
              that.msgError('主推款必须上传广告位图片')
              return
            }
            if (that.opraType === 'edit') {
              updateInfo(params).then(response => {
                if (response.code === 200) {
                  that.msgSuccess("修改成功");
                  that.open = false;
                  that.closeSelectedTag(that.$route);
                }
              });
            } else {
              addInfo(params).then(response => {
                if (response.code === 200) {
                  that.msgSuccess("新增成功");
                  that.open = false;
                  that.closeSelectedTag(that.$route);
                }
              });
            }
          }
        });
      },
      isActive(route) {
        return route.path === this.$route.path
      },
      closeSelectedTag(view) {
        this.$store.dispatch('tagsView/delView', view).then(({
          visitedViews
        }) => {
          if (this.isActive(view)) {
            this.toLastView(visitedViews, view)
          }
        })
      },
      toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView.fullPath)
        } else {
          if (view.name === 'Dashboard') {
            this.$router.replace({
              path: '/redirect' + view.fullPath
            })
          } else {
            this.$router.push('/')
          }
        }
      }
    }
  };
</script>

<style>
  .my-edit-container {
    margin: 0;
    padding: 30px 15px;
  }

  .title-bd {
    width: 100%;
    position: relative;
  }
  .btn-submit{
    width: 73px;
    text-align: center;
    font-size: 12px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #FFFFFF;
    background: #1890FF;
    border-radius: 2px;
    position: absolute;
    right: 0;
    bottom: 12px;
  }
  .title-name {
    font-size: 16px;
    font-weight: bold;
    color: #1890ff;
    margin-left: 12px;
    position: relative;
  }

  .title-name::before {
    display: inline-block;
    content: " ";
    width: 4px;
    height: 14px;
    background: #1890ff;
    position: absolute;
    left: -12px;
    bottom: 1.7px;
  }

  .hr {
    width: 100%;
    height: 1px;
    margin-top: 16px;
    background-color: #1890ff;
  }

  .select-product .el-input input:hover {
    cursor: pointer;
  }

  .myForm {
    padding-top: 22px;
    padding-bottom: 20px;
  }

  .my-form-footer {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }

  #editShareInfoForm .el-form-item__content {
    width: calc(100% - 100px);
  }

  #editShareInfoForm .el-form-item__content .el-input,
  #editShareInfoForm .el-form-item__content .el-select {
    width: 100%;
  }

  .video-opra-btns {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    margin-top: 15px;
  }
  #goodsInfoBox{
    width: 100%;
    display: flex;
  }
  #goodsInfoBox .info{
    flex: 1;
    display: flex;
    align-items: center;
  }
  #goodsInfoBox .info .el-form-item{
    padding: 0;
    margin: 0;
  }
  #goodsInfoBox .img{
    width: 80px;
    height: 80px;
    margin-left: 15px;
  }
  #uploadPicBox{
    width: 470px;
  }
  #uploadPicBox .el-upload-list__item{
    width: 148px;
  }
</style>
